<template>
  <div id="login">
    <app-head>Login</app-head>
    <form
      @submit.prevent="onLogin"
      class="needs-validation"
      :class="{'was-validated': wasValidated}"
      novalidate
    >
      <div class="form-group">
        <input
          class="form-control"
          v-model="username.value"
          type="text"
          placeholder="user name"
          required
        >
        <div v-if="!password.valid" :class="{'invalid-feedback': !username.valid}">请输入用户名</div>
      </div>
      <div class="form-group">
        <input
          class="form-control"
          v-model="password.value"
          type="password"
          placeholder="password"
          required
        >
        <div v-if="!password.valid" :class="{'invalid-feedback': !password.valid}">请输入密码</div>
      </div>
      <div class="form-group">
        <button class="btn btn-primary btn-block">Login</button>
      </div>
    </form>
    <pre>{{getToken}}</pre>
  </div>
</template>

<script>
import Head from '@/components/common/Head'
import { mapGetters, mapActions } from 'vuex'

export default {
  name: 'Login',
  data() {
    return {
      username: { value: null, valid: false },
      password: { value: null, valid: false },
      wasValidated: false,
      validation: false
    }
  },
  methods: {
    ...mapActions(['login']),
    onLogin() {
      this.wasValidated = true
      this.checkForm()
      if (this.validation) {
        this.login({
          username: this.username.value,
          password: this.password.value
        })
      }
    },
    checkForm() {
      this.username.valid = !!this.username.value
      this.password.valid = !!this.password.value
      this.validation = this.username.valid && this.password.valid
    }
  },
  computed: mapGetters(['getToken']),
  components: {
    'app-head': Head
  }
}
</script>

<style lang="scss" scoped>
</style>
